package org.rfs.ipodencoder;

import java.io.IOException;
import java.util.HashMap;

public class FFMpegOutputParserTask extends QOutputParser {
	HashMap<String, HashMap<String, String>> mVideoInfo;
	Signal1<FFMpegEncodeStatus> publishStatus = new Signal1<FFMpegEncodeStatus>();
	Signal0 encodingDone = new Signal0();
	
	public FFMpegOutputParserTask() {

	}
		
	public void run() {
		String line;
		FFMpegEncodeStatus encodeStatus = new FFMpegEncodeStatus();
		encodeStatus.totalframes = Math.round(Double.parseDouble(mVideoInfo.get(getFileName()).get("VIDEO_FPS")) * Double.parseDouble(mVideoInfo.get(getFileName()).get("LENGTH")));
		encodeStatus.filename = this.sFileName;
		encodeStatus.pass = this.sPass;
		encodeStatus.starttime = System.currentTimeMillis();
		try {
			while ((line = bReader.readLine()) != null) {
				if (line.startsWith("frame=")) {
//					System.out.println(line);
					// frame= 119 fps=119 q=2.0 size= 449kB time=4.82 bitrate=763.2kbits/s
					encodeStatus.frame = line.substring(line.indexOf("frame=") + 6,line.indexOf("fps") - 1).trim();
					encodeStatus.fps = line.substring(line.indexOf("fps=") + 4, line.indexOf("q=")).trim();
					encodeStatus.q = line.substring(line.indexOf("q=") + 2, line.indexOf("size=")).trim();
					encodeStatus.size = line.substring(line.indexOf("size=") + 5, line.indexOf("kB")).trim();
					encodeStatus.time = line.substring(line.indexOf("time=") + 5, line.indexOf("bitrate")).trim();
					encodeStatus.bitrate = line.substring(line.indexOf("bitrate=") + 8,line.indexOf("kbits/s")).trim();
					publishStatus(encodeStatus);
				}
			}
//			this.publishStatus.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//	public void encodingFinished() {
//		System.out.println("encoding finished");
//		encodingDone.emit();
//	}
	
	private void publishStatus(FFMpegEncodeStatus encodeStatus) {
		publishStatus.emit(encodeStatus);
	}

	public void initialize(HashMap<String, HashMap<String,String>> mVideoInfo) {
		this.mVideoInfo = mVideoInfo;
	}
}
